import 'package:flutter/material.dart';
import 'package:flutterapp2/building/buildinfo.dart';
import 'package:fluttertoast/fluttertoast.dart';

BuildInfo buildInfo;
GlobalKey _globalKey = GlobalKey();

_update() {
  /// 所在的widget第一帧绘制完成之后回调，第一帧绘制完成标志着已经Build完成
  WidgetsBinding.instance.addPostFrameCallback((callback) {
    debugPrint(" >> addPostFrameCallback}");
    _globalKey.currentState.setState(() {});
  });
}

class TestLifecyclePage extends StatefulWidget {
  @override
  _TestLifecyclePageState createState() => _TestLifecyclePageState();
}

class _TestLifecyclePageState extends State<TestLifecyclePage> {
  /// initState是StatefulWidget创建完后调用的第一个方法，而且只执行一次
  ValueNotifier<BuildInfo> _notifier = ValueNotifier(null);

  @override
  void initState() {
    super.initState();
    print('>> _TestLifecyclePageState initState');
  }

  @override
  void dispose() {
    super.dispose();
    print('>> _TestLifecyclePageState dispose');
  }

  @override
  Widget build(BuildContext context) {
    print('>> _TestLifecyclePageState build');
    return Scaffold(
      appBar: AppBar(
        key: _globalKey,
        title: TitleWidget(
          notifier: _notifier,
        ),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              setState(() {});
//              assert(false, '异常了');
            },
            child: Text("刷新父widget"),
          ),
          Divider(
            height: 30,
            thickness: 2,
            color: Colors.red,
          ),
          FutureBuilder<BuildInfo>(
            future: _mockData(),
            builder: (context, snapshot) {
              // 请求已结束
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  // 请求失败，显示错误
                  return Text("Error: ${snapshot.error}");
                } else {
                  print('>> FutureBuilder success.');
                  // 请求成功，显示数据
                  buildInfo = snapshot.data;
                  _notifier.value = buildInfo; // 修改数据，触发notifyListeners
//                  _update();
                  return ContentWidget();
                }
              } else {
                print('>> loading');
                // 请求未结束，显示loading
                return CircularProgressIndicator();
              }
            },
          ),
          Divider(
            height: 30,
            thickness: 2,
            color: Colors.red,
          ),
          _ChildWidgetB(
            notifier: _notifier,
          ),
        ],
      ),
    );
  }
}

Future<BuildInfo> _mockData() async {
  return Future.delayed(Duration(milliseconds: 1000), () {
    return BuildInfo(id: "1001", name: "张三");
  });
}

class ContentWidget extends StatefulWidget {
  const ContentWidget({Key key, this.data}) : super(key: key);
  final ValueNotifier<BuildInfo> data;

  @override
  _ContentWidgetState createState() => _ContentWidgetState();
}

class _ContentWidgetState extends State<ContentWidget> {
//  String title = '子widget';

  @override
  void initState() {
    super.initState();
    print('>> _ContentWidgetState initState');
  }

  /// didChangeDependencies在整个过程中可能会被调用多次, 但是也只有下面两种情况下会被调用
  /// 在StatefulWidget第一次创建的时候didChangeDependencies会被调用一次, 会在initState方法之后会被立即调用
  /// 从其他对象中依赖一些数据发生改变时, 比如所依赖的InheritedWidget状态发生改变时, 也会被调用
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('>> _ContentWidgetState didChangeDependencies');
  }

  /// 执行didUpdateWidget方法是在当父Widget触发重建时，系统会调用didUpdateWidget方法
  @override
  void didUpdateWidget(ContentWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    print('>> _ContentWidgetState didUpdateWidget');
  }

  @override
  void dispose() {
    super.dispose();
    print('>> _ContentWidgetState dispose');
    buildInfo = null;
    _globalKey = null;
  }

  @override
  Widget build(BuildContext context) {
    print('>> _ContentWidgetState build');
    return Column(
      children: <Widget>[
        Text('buildInfo.name = ' + buildInfo?.name ?? ""),
        RaisedButton(
          onPressed: () {
            setState(() {
              buildInfo?.name = "李四";
            });
          },
          child: Text("刷新子widget"),
        ),
      ],
    );
  }
}

class _ChildWidgetB extends StatefulWidget {
  const _ChildWidgetB({Key key, this.notifier}) : super(key: key);
  final ValueNotifier<BuildInfo> notifier;

  @override
  __ChildWidgetBState createState() => __ChildWidgetBState();
}

class __ChildWidgetBState extends State<_ChildWidgetB> {
  BuildInfo _info;

  @override
  void initState() {
    super.initState();
    widget.notifier.addListener(() {
      _info = widget.notifier.value;
      Fluttertoast.showToast(msg: _info?.name ?? '');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(_info?.name ?? ""),
    );
  }
}

class TitleWidget extends StatefulWidget {
  const TitleWidget({Key key, this.notifier}) : super(key: key);
  final ValueNotifier<BuildInfo> notifier;

  @override
  _TitleWidgetState createState() => _TitleWidgetState();
}

class _TitleWidgetState extends State<TitleWidget> {
  BuildInfo _info;

  @override
  void initState() {
    super.initState();
    widget.notifier.addListener(() {
      WidgetsBinding.instance.addPostFrameCallback((callback) {
        setState(() {
          _info = widget.notifier.value;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(_info?.name ?? "");
  }
}
